package com.example.jdbi.config;

import org.jdbi.v3.core.ConnectionFactory;
import org.jdbi.v3.core.Jdbi;
import org.jdbi.v3.sqlobject.SqlObjectPlugin;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.lang.NonNull;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbiFactoryBean extends AbstractFactoryBean<Jdbi> {
    private final Jdbi jdbi;

    public JdbiFactoryBean(DataSource dataSource) {
        ConnectionFactory connectionFactory = new SpringConnectionFactory(dataSource);
        this.jdbi = Jdbi.create(connectionFactory);
        this.jdbi.installPlugin(new SqlObjectPlugin());
    }

    @Override
    public Class<?> getObjectType() {
        return Jdbi.class;
    }

    @Override
    protected @NonNull Jdbi createInstance() throws Exception {
        return jdbi;
    }


    private record SpringConnectionFactory(DataSource dataSource) implements ConnectionFactory {
        @Override
        public Connection openConnection() throws SQLException {
            return DataSourceUtils.getConnection(dataSource);
        }

        @Override
        public void closeConnection(Connection connection) throws SQLException {
            DataSourceUtils.releaseConnection(connection, dataSource);
        }
    }
}
